package com.wws.family.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.wws.family.MyApp
import com.wws.family.db.dao.AccountDao
import com.wws.family.db.dao.NoteBookDao
import com.wws.family.db.dao.MedicineDao


/**
 *@Description: 数据库操作
 *@Date: 2024/11/04 14:26
 *@Author: WangWeiShuo
 */
@Database(
    entities = [MedicineBean::class,NoteBookBean::class,AccountBean::class],
    version = 1,
    exportSchema = false
)
abstract class WiKaDataBase : RoomDatabase() {
    abstract fun medicineDao(): MedicineDao
    abstract fun notebookDao(): NoteBookDao
    abstract fun accountDao(): AccountDao

    companion object {
        private const val DB_ENCODING = "UTF-8"
        private var instance: WiKaDataBase? = null
        fun getInstance(): WiKaDataBase {
            return instance ?: synchronized(this) {
                Room.databaseBuilder(
                    MyApp.applicationContext(),
                    WiKaDataBase::class.java,
                    "family_box"
                ).addCallback(roomCallback).build().also {
                    instance = it
                }
            }
        }

        private val roomCallback: Callback = object : Callback() {
            override fun onOpen(db: SupportSQLiteDatabase) {
                super.onOpen(db)
                // 设置数据库编码为UTF-8
                db.execSQL("PRAGMA foreign_keys=ON; PRAGMA encoding=\"$DB_ENCODING\";")
            }
        }

    }

    fun clearAll() {
        clearAllTables()
    }
}